/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.service.fr.procurement.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.bean.procurement.MaterialProcurementExcelBean;
import com.plian.system.bean.procurement.MaterialProcurementImportExcelBean;
import com.plian.system.constant.baseinfo.ValueSetConstant;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dto.fr.procurement.MaterialProcurementDTO;
import com.plian.system.entity.fr.procurement.MaterialProcurement;
import com.plian.system.entity.fr.procurement.ProcurementContract;
import com.plian.system.excel.ImportExcelUtil;
import com.plian.system.excel.ImportResult;
import com.plian.system.mapper.fr.procurement.MaterialProcurementMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.fr.procurement.IMaterialProcurementService;
import com.plian.system.service.fr.procurement.IProcurementContractService;
import com.plian.system.service.pm.property.PropertyService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.fr.procurement.MaterialProcurementVO;
import com.plian.system.vo.fr.procurement.ProcurementContractVO;
import com.plian.system.vo.fr.procurement.ProcurementSummaryChildVO;
import com.plian.system.vo.fr.procurement.ProcurementSummaryVO;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import com.plian.system.wrapper.fr.procurement.MaterialProcurementWrapper;
import com.plian.system.wrapper.fr.procurement.ProcurementContractWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 服务实现类
 *
 * @author
 * @since 2019-09-27
 */
@Slf4j
@Service
@AllArgsConstructor
public class MaterialProcurementServiceImpl extends BaseServiceImpl<MaterialProcurementMapper, MaterialProcurement> implements IMaterialProcurementService, BaseFlowService {

	private FormWorkflowService formWorkflowService;

	private IProcurementContractService procurementContractService;

	private IFormCodeService formCodeService;

	private PropertyService propertyService;

	private BaseInfoService baseInfoService;

	private OrgzationService orgzationService;

	private Environment environment;

	private FileService fileService;

	private MaterialProcurementWrapper materialProcurementWrapper;

	private ProcurementContractWrapper procurementContractWrapper;

	@Override
	public boolean saveOrUpdate(MaterialProcurement materialProcurement) {

		if (!Optional.ofNullable(materialProcurement.getStatus()).isPresent()) {
			materialProcurement.setStatus(FormStatusConstant.UNREVIEWED);
		}

		boolean flag = false;
		if (!Optional.ofNullable(materialProcurement.getId()).isPresent()) {
			flag = true;
			materialProcurement.setCode(formCodeService.getCode(FormTypeConstant.FR_MATERIAL_PROCUREMENT_FORM));
			materialProcurement.setFormType(String.valueOf(FormTypeConstant.FR_MATERIAL_PROCUREMENT_FORM));
		}

		boolean result = super.saveOrUpdate(materialProcurement);
		if (flag){
			fileService.saveAll(String.valueOf(materialProcurement.getId()), materialProcurement.getDocList());
		}else {
			fileService.edit(String.valueOf(materialProcurement.getId()), materialProcurement.getDocList());
		}
		return result;
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean deleteLogic(List<Long> ids) {
		for (Long id : ids) {
			MaterialProcurement materialProcurement = getById(id);
			if (materialProcurement == null) {
				return false;
			} else if (materialProcurement.getStatus() != null &&
					(materialProcurement.getStatus() != FormStatusConstant.STASH && materialProcurement.getStatus() != FormStatusConstant.UNREVIEWED)) {
				return false;
			}
			formWorkflowService.deleteProcessInstance(String.valueOf(id));
		}
		return super.deleteLogic(ids);
	}

	@Override
	public HashMap<String,Object> commit(String id) {
		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

		//将需要提交的流程变量返回，用于工作流侧
		return new HashMap<String,Object>();
	}

	@Override
	public Boolean finish(String id) {
		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
	}

	@Override
	public Boolean reject(String id, int formState, String comment) {
		return handleStatus(Long.valueOf(id), formState);
	}

	/**
	 * 统一处理状态机事件方法
	 *
	 * @param id          主键
	 * @param updateStatus  更新状态
	 * @return boolean
	 */
	private Boolean handleStatus(Long id, int updateStatus) {
		try {
			MaterialProcurement materialProcurement = getById(id);
			/**
			 * 设置审批人和审批时间
			 */
			if (updateStatus == FormStatusConstant.FINISH){
				materialProcurement.setApprovedUser(TokenUtil.getTokenUserId());
				Date now = DateUtil.now();
				materialProcurement.setApprovedTime(now);
			}
			materialProcurement.setStatus(updateStatus);
			updateById(materialProcurement);
			return true;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return false;
		}
	}


	@Override
	public List<PageData> findByIds(List<String> formIds) {
		LambdaQueryWrapper<MaterialProcurement> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(MaterialProcurement::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
		List<MaterialProcurement> materialProcurements = list(queryWrapper);
		List<MaterialProcurementVO> materialProcurementVOS= materialProcurementWrapper.entityToVO(materialProcurements);
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(materialProcurementVOS)){
				for (MaterialProcurementVO vo : materialProcurementVOS){
					PageData pd = new PageData();
					pd.put("id", vo.getId());
					pd.put("UNITNAME", vo.getProcurementCompanyName());
					pd.put("APPLICANTNAME", vo.getCreateUserName());
					pd.put("applicantId", vo.getCreateUser());
					pd.put("applyOrganizationId", vo.getFillingUnitId());
					pd.put("formType", FormTypeConstant.FR_MATERIAL_PROCUREMENT_FORM);
					pd.put("orgName", vo.getProcurementCompanyName());
					pageDataList.add(pd);
				}
			}

			return pageDataList;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		return pageDataList;
	}

	@Override
	public List<Integer> getFormType() {
		return Collections.singletonList(FormTypeConstant.FR_MATERIAL_PROCUREMENT_FORM);
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean submit(MaterialProcurement materialProcurement) {
		boolean result = saveOrUpdate(materialProcurement);
		if (result){

			List<ProcurementContract> procurementContracts = materialProcurement.getProcurementContracts();
			if (CollectionUtil.isNotEmpty(procurementContracts)){
				for (ProcurementContract procurementContract : procurementContracts){
					if (procurementContract.getId() != null &&
							Optional.ofNullable(procurementContract.getIsDeleted()).isPresent() && procurementContract.getIsDeleted().intValue() == 1) {
						procurementContractService.removeById(procurementContract.getId());
					}else {
						procurementContract.setMaterialProcurementId(materialProcurement.getId());
						procurementContractService.saveOrUpdate(procurementContract);
					}
				}
			}
		}

		return result;
	}

	@Override
	public R<MaterialProcurementVO> getDetailObj(MaterialProcurementVO materialProcurementVO) {
		materialProcurementVO.setProcurementContractVOS(procurementContractWrapper.entityToVO(procurementContractService.list(new LambdaQueryWrapper<ProcurementContract>()
				.eq(ProcurementContract::getMaterialProcurementId, materialProcurementVO.getId()))));
		return R.data(materialProcurementVO);
	}

	@Override
	public ListResult<MaterialProcurementVO> list(Query query) {
		List<SearchEntity> entityList = query.getSearch();
		if (query.getAscs()==null&&query.getDescs()==null){
			query.setDescs("create_time");
		}
		QueryWrapper<MaterialProcurement> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new MaterialProcurement()), entityList
		);
		TokenSearch<MaterialProcurement> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);

		IPage<MaterialProcurement> pages = page(Condition.getPage(query), queryWrapper);
		List<MaterialProcurementVO> materialProcurementVOS = materialProcurementWrapper.entityToVO(pages.getRecords());
		if (CollectionUtil.isNotEmpty(materialProcurementVOS)){
			List<ProcurementContractVO> procurementContractVOS = procurementContractWrapper.entityToVO(procurementContractService
					.list(new LambdaQueryWrapper<ProcurementContract>().in(ProcurementContract::getMaterialProcurementId,
							materialProcurementVOS.stream().map(MaterialProcurementVO::getId).collect(Collectors.toList()))));
			Map<Long, List<ProcurementContractVO>> map = new HashMap<>(materialProcurementVOS.size());
			if (CollectionUtil.isNotEmpty(procurementContractVOS)){
				map = procurementContractVOS.stream().collect(Collectors.groupingBy(ProcurementContractVO::getMaterialProcurementId));
			}

			for (MaterialProcurementVO vo : materialProcurementVOS){
				if (CollectionUtil.isNotEmpty(map) && map.containsKey(vo.getId())){
					vo.setProcurementContractVOS(map.get(vo.getId()));
				}
			}
		}
		ListResult<MaterialProcurementVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(materialProcurementVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;

	}

	@Override
	public void goBackToStash(String formId) {
		handleStatus(Long.valueOf(formId), UNREVIEWED);
	}

	@Override
	public List<ProcurementSummaryVO> summary(MaterialProcurementDTO materialProcurementDTO) {
		List<ProcurementSummaryChildVO> procurementSummaryChildVOS = baseMapper.summary(materialProcurementDTO.getFillingYear(), materialProcurementDTO.getFillingUnitIds());
		List<ProcurementSummaryVO> results = unitInit(materialProcurementDTO.getFillingUnitIds());
		if (CollectionUtil.isEmpty(results) || CollectionUtil.isEmpty(procurementSummaryChildVOS)){
			return results;
		}

		// 单位id加采购分类id
		Map<String, ProcurementSummaryChildVO> dataMap = new HashMap<>(64);
		for (ProcurementSummaryChildVO data : procurementSummaryChildVOS){
			dataMap.put(data.getFillingUnitId() + "-" + data.getProcurementCategoryId(), data);
		}

		ProcurementSummaryVO two = results.get(1);
		for (int i = 2; i < results.size(); i++){
			ProcurementSummaryVO procurementSummaryVO = results.get(i);
			List<ProcurementSummaryChildVO> childVOS = procurementSummaryVO.getChildVOS();
			for (ProcurementSummaryChildVO childVO : childVOS){
				String key = procurementSummaryVO.getFillingUnitId() + "-" + childVO.getProcurementCategoryId();

				if(dataMap.containsKey(key)){
					ProcurementSummaryChildVO data = dataMap.get(key);
					data.setProcurementCategoryName(childVO.getProcurementCategoryName());
					BeanUtils.copyProperties(data, childVO);
					// 当无预算个数大于0时 填充备注
					if (Optional.ofNullable(childVO.getRemarkNumber()).isPresent()
						&& childVO.getRemarkNumber() > 0){
						childVO.setRemark(childVO.getRemarkNumber() + "个无预算");
					}

					//合计
					for (ProcurementSummaryChildVO twoChild : two.getChildVOS()){
						if (childVO.getProcurementCategoryId().equals(twoChild.getProcurementCategoryId())){
							twoChild.setBudget(twoChild.getBudget().add(childVO.getBudget()));
							twoChild.setProcurementNumber(twoChild.getProcurementNumber() + childVO.getProcurementNumber());
							twoChild.setProcurementContractAmount(twoChild.getProcurementContractAmount().add(childVO.getProcurementContractAmount()));
							twoChild.setProcurementCoverCharge(twoChild.getProcurementCoverCharge().add(childVO.getProcurementCoverCharge()));
							twoChild.setQualityProductsProcurement(twoChild.getQualityProductsProcurement().add(childVO.getQualityProductsProcurement()));
							twoChild.setInnovationProductsProcurement(twoChild.getInnovationProductsProcurement().add(childVO.getInnovationProductsProcurement()));
							twoChild.setCreditEnterprisesProcurement(twoChild.getCreditEnterprisesProcurement().add(childVO.getCreditEnterprisesProcurement()));
							twoChild.setRemarkNumber(twoChild.getRemarkNumber() + childVO.getRemarkNumber());
							break;
						}
					}

					//合计 合计栏数据
					two.setTotalBudget(two.getTotalBudget().add(childVO.getBudget()));
					two.setTotalProjectNumber(two.getTotalProjectNumber() + childVO.getProcurementNumber());
					two.setTotalContractAmount(two.getTotalContractAmount().add(childVO.getProcurementContractAmount()));
					two.setTotalCoverCharge(two.getTotalCoverCharge().add(childVO.getProcurementCoverCharge()));
					two.setTotalQualityProducts(two.getTotalQualityProducts().add(childVO.getQualityProductsProcurement()));
					two.setTotalInnovationProducts(two.getTotalInnovationProducts().add(childVO.getInnovationProductsProcurement()));
					two.setTotalCreditEnterprises(two.getTotalCreditEnterprises().add(childVO.getCreditEnterprisesProcurement()));

					// 合计栏 数据
					procurementSummaryVO.setTotalBudget(procurementSummaryVO.getTotalBudget().add(childVO.getBudget()));
					procurementSummaryVO.setTotalProjectNumber(procurementSummaryVO.getTotalProjectNumber() + childVO.getProcurementNumber());
					procurementSummaryVO.setTotalContractAmount(procurementSummaryVO.getTotalContractAmount().add(childVO.getProcurementContractAmount()));
					procurementSummaryVO.setTotalCoverCharge(procurementSummaryVO.getTotalCoverCharge().add(childVO.getProcurementCoverCharge()));
					procurementSummaryVO.setTotalQualityProducts(procurementSummaryVO.getTotalQualityProducts().add(childVO.getQualityProductsProcurement()));
					procurementSummaryVO.setTotalInnovationProducts(procurementSummaryVO.getTotalInnovationProducts().add(childVO.getInnovationProductsProcurement()));
					procurementSummaryVO.setTotalCreditEnterprises(procurementSummaryVO.getTotalCreditEnterprises().add(childVO.getCreditEnterprisesProcurement()));
				}
			}
		}


		two.setQualityProductsProportion(two.getTotalQualityProducts().divide(two.getTotalContractAmount()));
		two.setInnovationProductsProportion(two.getTotalInnovationProducts().divide(two.getTotalContractAmount()));
		two.setCreditEnterprisesProportion(two.getTotalCreditEnterprises().divide(two.getTotalContractAmount()));

		// 总计 数据填充
		ProcurementSummaryVO one = results.get(0);
		ProcurementSummaryChildVO oneChild = one.getChildVOS().get(0);
		for (ProcurementSummaryChildVO twoChild : two.getChildVOS()){
			oneChild.setBudget(oneChild.getBudget().add(twoChild.getBudget()));
			oneChild.setProcurementNumber(oneChild.getProcurementNumber() + twoChild.getProcurementNumber());
			oneChild.setProcurementContractAmount(oneChild.getProcurementContractAmount().add(twoChild.getProcurementContractAmount()));
			oneChild.setProcurementCoverCharge(oneChild.getProcurementCoverCharge().add(twoChild.getProcurementCoverCharge()));
			oneChild.setQualityProductsProcurement(oneChild.getQualityProductsProcurement().add(twoChild.getQualityProductsProcurement()));
			oneChild.setInnovationProductsProcurement(oneChild.getInnovationProductsProcurement().add(twoChild.getInnovationProductsProcurement()));
			oneChild.setCreditEnterprisesProcurement(oneChild.getCreditEnterprisesProcurement().add(twoChild.getCreditEnterprisesProcurement()));
			oneChild.setRemarkNumber(oneChild.getRemarkNumber() + twoChild.getRemarkNumber());

			// 当无预算个数大于0时 填充备注
			if (twoChild.getRemarkNumber() > 0){
				twoChild.setRemark(twoChild.getRemarkNumber() + "个无预算");
			}

		}
		// 当无预算个数大于0时 填充备注
		if (oneChild.getRemarkNumber() > 0){
			oneChild.setRemark(oneChild.getRemarkNumber() + "个无预算");
		}

		return results;
	}

	@Override
	public ReportReturnVO typeSummary(MaterialProcurementDTO materialProcurementDTO) {
		ReportVO reportVO = new ReportVO();
		String orderSql = "";
		String groupSql = "";
		ProcurementSummaryChildVO end = ProcurementSummaryChildVO.builder()
				.budget(new BigDecimal(0)).procurementContractAmount(new BigDecimal(0)).procurementNumber(0)
				.procurementCoverCharge(new BigDecimal(0)).qualityProductsProcurement(new BigDecimal(0))
				.innovationProductsProcurement(new BigDecimal(0)).creditEnterprisesProcurement(new BigDecimal(0)).build();
		boolean flag = true;
		// 填报单位
		if (materialProcurementDTO.getOneStatus()){
			reportVO.addHeader(HeaderVO.builder().key("fillingUnitName").title("汇总企业").build());
			orderSql += " p.filling_unit_id";
			groupSql += " p.filling_unit_id";
			end.setFillingUnitName("合计");
			flag = false;
		}

		// 填报单位
		if (materialProcurementDTO.getTwoStatus()){
			reportVO.addHeader(HeaderVO.builder().key("procurementCompanyName").title("采购单位").build());

			if (StringUtil.isNotBlank(orderSql)){
				orderSql += ",";
			}
			orderSql += " p.procurement_company_name";
			if (StringUtil.isNotBlank(groupSql)){
				groupSql += ",";
			}
			groupSql += " p.procurement_company_name";

			if (flag){
				end.setProcurementCompanyName("合计");
				flag = false;
			}else {
                end.setProcurementCompanyName("-");
            }
		}

		//采购分类
		if (materialProcurementDTO.getThreeStatus()){
			reportVO.addHeader(HeaderVO.builder().key("procurementCategoryName").title("采购分类").build());

			if (StringUtil.isNotBlank(orderSql)){
				orderSql += ",";
			}
			orderSql += " p.procurement_category_id";
			if (StringUtil.isNotBlank(groupSql)){
				groupSql += ",";
			}
			groupSql += " p.procurement_category_id,pcb.NAME";

			if (flag){
				end.setProcurementCategoryName("合计");
				flag = false;
			}else {
                end.setProcurementCategoryName("-");
            }
		}

		//采购平台
		if (materialProcurementDTO.getFourStatus()){
			reportVO.addHeader(HeaderVO.builder().key("procurementPlatformCategoryName").title("采购平台").build());

			if (StringUtil.isNotBlank(orderSql)){
				orderSql += ",";
			}
			orderSql += " p.procurement_platform_category_id";
			if (StringUtil.isNotBlank(groupSql)){
				groupSql += ",";
			}
			groupSql += " p.procurement_platform_category_id,ppb.NAME";

			if (flag){
				end.setProcurementPlatformCategoryName("合计");
				flag = false;
			}else {
                end.setProcurementPlatformCategoryName("-");
            }
		}

		//采购方式
		if (materialProcurementDTO.getFiveStatus()){
			reportVO.addHeader(HeaderVO.builder().key("procurementWayName").title("采购方式").build());
			if (StringUtil.isNotBlank(orderSql)){
				orderSql += ",";

			}
			orderSql += " p.procurement_way_id";
			if (StringUtil.isNotBlank(groupSql)){
				groupSql += ",";
			}
			groupSql += " p.procurement_way_id,pwb.NAME";

			if (flag){
				end.setProcurementWayName("合计");
			}else {
                end.setProcurementWayName("-");
            }
		}

		materialProcurementDTO.setOrderSql(orderSql);
		materialProcurementDTO.setGroupSql(groupSql);
		List<ProcurementSummaryChildVO> dataList = baseMapper.summaryByType(materialProcurementDTO);

		reportVO.addHeader(HeaderVO.builder().key("budget").title("预算金额").build());
		reportVO.addHeader(HeaderVO.builder().key("procurementContractAmount").title("采购合同金额").build());
		reportVO.addHeader(HeaderVO.builder().key("procurementNumber").title("采购项目数").build());
		reportVO.addHeader(HeaderVO.builder().key("procurementCoverCharge").title("采购支付服务费用金额").build());
		reportVO.addHeader(HeaderVO.builder().key("qualityProductsProcurement").title("其中宁波优质产品采购额").build());
		reportVO.addHeader(HeaderVO.builder().key("innovationProductsProcurement").title("其中宁波自主创新产品采购额").build());
		reportVO.addHeader(HeaderVO.builder().key("creditEnterprisesProcurement").title("其中宁波市信用示范小微企业产品采购额").build());

		List<ProcurementSummaryChildVO> results = new ArrayList<>();
		if (CollectionUtil.isNotEmpty(dataList)){
			results.add(end);
			for (ProcurementSummaryChildVO result : dataList){
				end.setBudget(end.getBudget().add(result.getBudget()));
				end.setProcurementContractAmount(end.getProcurementContractAmount().add(result.getProcurementContractAmount()));
				end.setProcurementNumber(end.getProcurementNumber() + result.getProcurementNumber());
				end.setProcurementCoverCharge(end.getProcurementCoverCharge().add(result.getProcurementCoverCharge()));
				end.setQualityProductsProcurement(end.getQualityProductsProcurement().add(result.getQualityProductsProcurement()));
				end.setInnovationProductsProcurement(end.getInnovationProductsProcurement().add(result.getInnovationProductsProcurement()));
				end.setCreditEnterprisesProcurement(end.getCreditEnterprisesProcurement().add(result.getCreditEnterprisesProcurement()));
				results.add(result);
			}

		}

		ReportReturnVO reportReturnVO = new ReportReturnVO();
		reportVO.setData(results);
		reportReturnVO.setGrids(reportVO);
		return reportReturnVO;
	}

	@Override
	public String exportDetail(Query query) {
		String key = TokenUtil.getTokenUserId() + "-" + UUID.randomUUID().toString().replace("-", "");
		List<SearchEntity> entityList = query.getSearch();
		if (query.getAscs()==null&&query.getDescs()==null){
			query.setDescs("create_time");
		}
		QueryWrapper<MaterialProcurement> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new MaterialProcurement()), entityList
		);
		List<MaterialProcurement> materialProcurements = list(queryWrapper);

		if (CollectionUtil.isNotEmpty(materialProcurements)){
			QueryWrapper<ProcurementContract> contractQueryWrapper = new QueryWrapper<>();
			contractQueryWrapper.in("material_procurement_id", materialProcurements.stream()
					.map(MaterialProcurement::getId).collect(Collectors.toList()));
			Map<Long, List<ProcurementContract>> childMap = procurementContractService.list(contractQueryWrapper).stream()
					.collect(Collectors.groupingBy(ProcurementContract::getMaterialProcurementId));
			List<PageData> allList =  (List<PageData>)orgzationService.listAll().getPageData().get("list");
			HashMap<String, String> orgMap = new HashMap<>();
			//单位
			if (CollectionUtil.isNotEmpty(allList)) {
				for (PageData pageData : allList) {
					orgMap.put((String) pageData.get("id"), (String) pageData.get("name"));
				}
			}

			//值级
			Map<String, String> procurementCategoryMap = baseInfoService.getChildMap(ValueSetConstant.PROCUREMENT_CATEGORY);
			Map<String, String> procurementWayMap = baseInfoService.getChildMap(ValueSetConstant.PROCUREMENT_WAY);
			Map<String, String> rankMap = baseInfoService.getChildMap(ValueSetConstant.ENTERPRISE_RANK);


			Integer index = 0;
			List<MaterialProcurementExcelBean> results = new ArrayList<>();
			for (MaterialProcurement materialProcurement : materialProcurements){
				index++;
				MaterialProcurementExcelBean materialProcurementExcelBean = new MaterialProcurementExcelBean();
				BeanUtils.copyProperties(materialProcurement, materialProcurementExcelBean);
				materialProcurementExcelBean.setIndex(index);
				materialProcurementExcelBean.setFillingUnitName(orgMap.get(materialProcurement.getFillingUnitId()));
				materialProcurementExcelBean.setProcurementCategoryName(procurementCategoryMap.get(materialProcurement.getProcurementCategoryId()));
				materialProcurementExcelBean.setProcurementWayName(procurementWayMap.get(materialProcurement.getProcurementWayId()));
				materialProcurementExcelBean.setProcurementCompanyRankName(rankMap.get(materialProcurement.getProcurementCompanyRankId()));
				materialProcurementExcelBean.setIsSupplementaryContractStr(materialProcurement.getIsSupplementaryContract() == 1 ? "否" : "是");
				if (childMap.containsKey(materialProcurement.getId())){
					List<ProcurementContract> procurementContracts = childMap.get(materialProcurement.getId());
					// 合同列表
					for (int i = 0; i<procurementContracts.size(); i++){
						ProcurementContract procurementContract = procurementContracts.get(i);
						String contractTimeStr = "";
						String contractExecutionTimeStr = "";
						// 合同时间处理
						if (Optional.ofNullable(procurementContract.getIsSigned()).isPresent() && procurementContract.getIsSigned() == 2){
							if (Optional.ofNullable(procurementContract.getContractStartTime()).isPresent()){
								contractTimeStr = DateUtil.formatDate(procurementContract.getContractStartTime());
							}
							if (Optional.ofNullable(procurementContract.getContractEndTime()).isPresent()){
								if (StringUtil.isNotBlank(contractTimeStr)){
									contractTimeStr += "-" + DateUtil.formatDate(procurementContract.getContractEndTime());
								}else {
									contractTimeStr = DateUtil.formatDate(procurementContract.getContractEndTime());
								}
							}

							if (Optional.ofNullable(procurementContract.getContractExecutionStartTime()).isPresent()){
								contractExecutionTimeStr = DateUtil.formatDate(procurementContract.getContractExecutionStartTime());
							}
							if (Optional.ofNullable(procurementContract.getContractExecutionEndTime()).isPresent()){
								if (StringUtil.isNotBlank(contractExecutionTimeStr)){
									contractExecutionTimeStr += "-" + DateUtil.formatDate(procurementContract.getContractExecutionEndTime());
								}else {
									contractExecutionTimeStr = DateUtil.formatDate(procurementContract.getContractExecutionEndTime());
								}
							}

						}else {
							contractTimeStr = "无";
						}

						if (i == 0){
							materialProcurementExcelBean.setContractNumber(procurementContract.getContractNumber());
							//合同时间处理
							materialProcurementExcelBean.setContractTimeStr(contractTimeStr);
							materialProcurementExcelBean.setContractExecutionTimeStr(contractExecutionTimeStr);
							results.add(materialProcurementExcelBean);
						}else {
							//合同多个时特殊处理
							MaterialProcurementExcelBean bean = new MaterialProcurementExcelBean();
							bean.setContractNumber(procurementContract.getContractNumber());
							bean.setContractTimeStr(contractTimeStr);
							bean.setContractExecutionTimeStr(contractExecutionTimeStr);
							results.add(bean);
						}
					}

				}else {
					results.add(materialProcurementExcelBean);
				}
			}

			String fileName = key + ".xlsx";
			String exportPath = environment.getProperty("excel.path");

			/**
			 * 导出路径不存在则创建
			 */
			File file = new File(exportPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			InputStream inputStream = this.getClass().getResourceAsStream("/exceldemo/materialProcurement.xlsx");
			ExcelWriter excelWriter = EasyExcel.write(exportPath + fileName).withTemplate(inputStream).build();

			WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
			FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
			excelWriter.fill(new FillWrapper("data", results), fillConfig, writeSheet);
			excelWriter.finish();
		}
		return key;
	}

	@Override
	public void download(String key, HttpServletResponse response, OutputStream os) {
		String excelName = "大宗物资采购明细列表";
		String excelPath = environment.getProperty("excel.path") + "/" + key + ".xlsx";

		try {
			os = response.getOutputStream();//取得输出流
			response.reset();//清空输出流
			//下面是对中文文件名的处理
			response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式

			InputStream inputStream = new FileInputStream(excelPath);
			excelName = java.net.URLEncoder.encode(excelName, "UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(excelName.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8) + ".xlsx");

			response.setContentType("application/msexcel");//定义输出类型
			int len;
			byte[] b = new byte[2048];
			while ((len = inputStream.read(b)) != -1) {
				os.write(b, 0, len);
			}
			response.setHeader("Content-Length", String.valueOf(inputStream.available()));

			inputStream.close();
			os.close();
		}catch (Exception e){
			log.error(ExceptionUtils.getFullStackTrace(e));
		}finally {
			/**
			 * 删除文件
			 */
			File file = new File(excelPath);
			if(file.exists() && file.isFile()){
				file.delete();
			}
		}
	}

	@Override
	public void exportTemplateExcel(HttpServletResponse response, OutputStream os) {
		try {
			String fname = "大宗物资采购信息导入模板";
			os = response.getOutputStream();//取得输出流
			response.reset();//清空输出流
			//下面是对中文文件名的处理
			response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
			InputStream inputStream = this.getClass().getResourceAsStream("/exceldemo/materialProcurementImport.xlsx");
			fname = java.net.URLEncoder.encode(fname, "UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(fname.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8) + ".xlsx");

			response.setContentType("application/msexcel");//定义输出类型
			int len;
			byte[] b = new byte[2048];
			while ((len = inputStream.read(b)) != -1) {
				os.write(b, 0, len);
			}
			response.setHeader("Content-Length", String.valueOf(inputStream.available()));

			inputStream.close();
			os.close();
		}catch (Exception e){
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
	}

	@Override
	@Async("ttlExecutor")
	public Future<ImportResult> importExcel(String progressId, InputStream inputStream) {
		String progress = "progress";
		String key = progressId + "#half:hour";
		try {
			byte[] bytes = IOUtils.toByteArray(inputStream);
			inputStream = new ByteArrayInputStream(bytes);

			Map<String, Map<String, String>> mapRef = getRef();

            List<Object> excelList = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(1).headRowNumber(1).head(MaterialProcurementImportExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> excelList.addAll(list))).build());

			List<MaterialProcurement> existList = list(new QueryWrapper<MaterialProcurement>().eq("status", FormStatusConstant.FINISH));
			List<String> existNameList = existList.stream().map(materialProcurement -> materialProcurement.getFillingYear() + "_"
					+ materialProcurement.getProcurementCompanyName() + "_"
					+ materialProcurement.getProcurementProject() + "_"
					+ materialProcurement.getCreateCompanyId()).collect(Collectors.toList());
			ImportExcelUtil.filterEmpty(excelList);
			ImportResult result = checkData(mapRef, excelList, progressId, existNameList);
			if (!result.isSuccess()){
				CacheUtil.put(progress, progress, key, result.getMsg());
				return new AsyncResult<>(result);
			}


			int count = 0;
			int size = excelList.size();

			String orgId = TokenUtil.getTokenOrgId();
			PageData pd = new PageData();
			pd.put("orgId", orgId);
			PageData groupOrg = orgzationService.getGroupbyId(pd).getPageData();
			String fillingUnitId = "";
			if (groupOrg != null){
				fillingUnitId = groupOrg.getString("id");
			}
			// 项目信息
			for (Object readExcel : excelList) {
				MaterialProcurement materialProcurement = (MaterialProcurement) ImportExcelUtil.getEntityByExcelBean(readExcel,new MaterialProcurement());

				QueryWrapper<MaterialProcurement> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("filling_year", materialProcurement.getFillingYear());
				queryWrapper.eq("create_company_id", orgId);
				queryWrapper.eq("procurement_company_name", materialProcurement.getProcurementCompanyName());
				queryWrapper.eq("procurement_project", materialProcurement.getProcurementProject());
				MaterialProcurement old = getOne(queryWrapper);
				if (Optional.ofNullable(old).isPresent()){
					materialProcurement.setId(old.getId());
				}else {
					materialProcurement.setCode(formCodeService.getCode(FormTypeConstant.FR_MATERIAL_PROCUREMENT_FORM));
					materialProcurement.setFormType(String.valueOf(FormTypeConstant.FR_MATERIAL_PROCUREMENT_FORM));
					materialProcurement.setStatus(FormStatusConstant.UNREVIEWED);
				}
				if (StringUtil.isNotBlank(fillingUnitId)){
					materialProcurement.setFillingUnitId(fillingUnitId);
				}

				//入库
				try {
					saveOrUpdate(materialProcurement);
					count++;
					int value = count * 100 / size;
					CacheUtil.put(progress, progress, key, value+100);
				} catch (Exception e) {
					log.error(materialProcurement + "导入失败");
					CacheUtil.put(progress, progress, key,materialProcurement + "导入失败");
					return new AsyncResult<>(new ImportResult(false,materialProcurement + "导入失败"));
				}
			}

		}catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			log.error("解析失败");
			CacheUtil.put(progress, progress, key,"解析失败");
			return new AsyncResult<>(new ImportResult(false,"解析失败"));
		}

		CacheUtil.put(progress, progress, key,"导入成功");
		return new AsyncResult<>(new ImportResult(true,"导入成功"));
	}

	private Map<String,Map<String,String>> getRef() {
		Map<String, Map<String, String>> mapRefs = new HashMap<>(16);
		mapRefs.put("enterpriseRankRef", baseInfoService.getChildMap(ValueSetConstant.ENTERPRISE_RANK));
		mapRefs.put("procurementCategoryRef", baseInfoService.getChildMap(ValueSetConstant.PROCUREMENT_CATEGORY));
		mapRefs.put("procurementWayRef", baseInfoService.getChildMap(ValueSetConstant.PROCUREMENT_WAY));
		mapRefs.put("platformCategoryRef", baseInfoService.getChildMap(ValueSetConstant.PROCUREMENT_PLATFORM_CATEGORY));

		return mapRefs;
	}


	private ImportResult checkData(Map<String, Map<String,String>> mapRef, List<Object> readExcels, String progressId, List<String> existNameList) {
		ImportResult importResult = new ImportResult(true,"");

		StringBuilder msg = new StringBuilder();

		if (CollectionUtil.isNotEmpty(readExcels)) {
			for (Object readExcel : readExcels) {
				MaterialProcurementImportExcelBean excelBean = (MaterialProcurementImportExcelBean) readExcel;
				int index = readExcels.indexOf(readExcel) + 2;

				//判空
				msg.append(ImportExcelUtil.checkEmpty("2", "年度",
						excelBean.getFillingYear(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购单位",
						excelBean.getProcurementCompanyName(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购企业级次",
						excelBean.getProcurementCompanyRankId(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购项目",
						excelBean.getProcurementProject(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购分类",
						excelBean.getProcurementCategoryId(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购平台分类",
						excelBean.getProcurementPlatformCategoryId(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购平台名称",
						excelBean.getProcurementPlatform(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购方式",
						excelBean.getProcurementWayId(), index).getMsg());

				msg.append(ImportExcelUtil.checkEmpty("2", "预算金额",
						excelBean.getBudget(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购合同金额",
						excelBean.getProcurementContractAmount(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购发生服务费用金额",
						excelBean.getProcurementCoverCharge(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "是否签订补充合同",
						excelBean.getIsSupplementaryContract(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "其中：宁波优质产品采购额",
						excelBean.getQualityProductsProcurement(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购占比%（宁波优质产品采购额）",
						excelBean.getQualityProductsProportion(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "其中：宁波自主创新产品采购额",
						excelBean.getInnovationProductsProcurement(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购占比%（宁波自主创新产品采购额）",
						excelBean.getInnovationProductsProportion(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "其中：宁波市信用示范小微企业产品采购额",
						excelBean.getCreditEnterprisesProcurement(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "采购占比%（宁波市信用示范小微企业产品采购额）",
						excelBean.getCreditEnterprisesProportion(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "供应商",
						excelBean.getSupplier(), index).getMsg());
				msg.append(ImportExcelUtil.checkEmpty("2", "代理机构名称",
						excelBean.getAgencyName(), index).getMsg());

				//类型判断
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "预算金额",
						excelBean.getBudget(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "采购合同金额",
						excelBean.getProcurementContractAmount(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "采购发生服务费用金额",
						excelBean.getProcurementCoverCharge(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "其中宁波优质产品采购额",
						excelBean.getQualityProductsProcurement(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "采购占比%（宁波优质产品采购额）",
						excelBean.getQualityProductsProportion(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "其中：宁波自主创新产品采购额",
						excelBean.getInnovationProductsProcurement(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "采购占比%（宁波自主创新产品采购额）",
						excelBean.getInnovationProductsProportion(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "其中：宁波市信用示范小微企业产品采购额",
						excelBean.getCreditEnterprisesProcurement(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "采购占比%（宁波市信用示范小微企业产品采购额）",
						excelBean.getCreditEnterprisesProportion(), index).getMsg());

				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_INTEGER, "2", "是否签订补充合同",
						excelBean.getIsSupplementaryContract(), index).getMsg());
				msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_INTEGER, "2", "年度",
						excelBean.getFillingYear(), index).getMsg());

			}
			//判断完类型若有错直接返回
			if (msg.toString().length() > 0) {
				return new ImportResult(false, msg.toString());
			}

			//对象和字典是否存在校验
			int size = readExcels.size();
			int count = 0;
			for (Object readExcel : readExcels) {
				MaterialProcurementImportExcelBean excelBean = (MaterialProcurementImportExcelBean) readExcel;
				int index = readExcels.indexOf(readExcel) + 2;
				String key = excelBean.getFillingYear() + "_"
						+ excelBean.getProcurementCompanyName() + "_"
						+ excelBean.getProcurementProject() + "_"
						+ TokenUtil.getTokenOrgId();

				if (existNameList.contains(key)){
					msg.append("sheet2第" + index + "行(采购项目=" + excelBean.getProcurementCompanyName() + ") 已存在且已审批\n");
				}
				if (StringUtil.isNotBlank(excelBean.getIsSupplementaryContract())){
					if (!"1".equals(excelBean.getIsSupplementaryContract()) && !"2".equals(excelBean.getIsSupplementaryContract())){
						msg.append("sheet2第" + index + "行(是否签订补充合同=" + excelBean.getIsSupplementaryContract() + ") 不是1或者2\n");
					}
				}

				//采购企业级次
				if (StringUtil.isNotBlank(excelBean.getProcurementCompanyRankId())) {
					if (!mapRef.get("enterpriseRankRef").containsKey(excelBean.getProcurementCompanyRankId())) {
						msg.append("sheet2第" + index + "行(采购企业级次=" + excelBean.getProcurementCompanyRankId() + ")在系统中不存在\n");
					}
				}

				if (StringUtil.isNotBlank(excelBean.getProcurementCategoryId())) {
					if (!mapRef.get("procurementCategoryRef").containsKey(excelBean.getProcurementCategoryId())) {
						msg.append("sheet2第" + index + "行(采购分类=" + excelBean.getProcurementCategoryId() + ")在系统中不存在\n");
					}
				}

				if (StringUtil.isNotBlank(excelBean.getProcurementWayId())) {
					if (!mapRef.get("procurementWayRef").containsKey(excelBean.getProcurementWayId())) {
						msg.append("sheet2第" + index + "行(采购方式=" + excelBean.getProcurementWayId() + ")在系统中不存在\n");
					}
				}

				if (StringUtil.isNotBlank(excelBean.getProcurementPlatformCategoryId())) {
					if (!mapRef.get("platformCategoryRef").containsKey(excelBean.getProcurementPlatformCategoryId())) {
						msg.append("sheet2第" + index + "行(采购平台分类=" + excelBean.getProcurementPlatformCategoryId() + ")在系统中不存在\n");
					}
				}

				count++;
				int value = count * 100 / size;
				CacheUtil.put("progress","progress",progressId, value);
			}
		}

		//统一放置报错
		if (msg.toString().length()>0) {
			importResult = new ImportResult(false, msg.toString());
		}
		return importResult;

	}

	/**
	 * 一级企业
	 * @return
	 */
	private  List<ProcurementSummaryVO> unitInit(List<String> fillingUnitIds) {
		List<PageData> firstCompanys = propertyService.allFirstCompany();
		List<ProcurementSummaryVO> init = new ArrayList<>();
		int index = 1;
		Map<String, String> procurementCategoryMap = baseInfoService.getChildMap(ValueSetConstant.PROCUREMENT_CATEGORY);
		if (CollectionUtil.isNotEmpty(firstCompanys)){
			// 总计
			ProcurementSummaryVO one = ProcurementSummaryVO.builder().fillingUnitName("总计").build();
			List<ProcurementSummaryChildVO> oneList = new ArrayList<>();
			oneList.add(ProcurementSummaryChildVO.builder().budget(new BigDecimal(0))
					.procurementNumber(0).procurementContractAmount(new BigDecimal(0))
					.procurementCoverCharge(new BigDecimal(0)).qualityProductsProcurement(new BigDecimal(0))
					.innovationProductsProcurement(new BigDecimal(0)).creditEnterprisesProcurement(new BigDecimal(0))
					.remarkNumber(0).build());

			// 合计
			ProcurementSummaryVO two = ProcurementSummaryVO.builder().fillingUnitName("合计")
					.totalBudget(new BigDecimal(0)).totalProjectNumber(0).totalContractAmount(new BigDecimal(0))
					.totalCoverCharge(new BigDecimal(0)).totalQualityProducts(new BigDecimal(0)).totalInnovationProducts(new BigDecimal(0))
					.totalCreditEnterprises(new BigDecimal(0)).build();
			List<ProcurementSummaryChildVO> twoList = new ArrayList<>();
			procurementCategoryMap.forEach((k,v) ->
					twoList.add(ProcurementSummaryChildVO.builder().procurementCategoryId(k).procurementCategoryName(v)
							.budget(new BigDecimal(0)).procurementNumber(0).procurementContractAmount(new BigDecimal(0))
							.procurementCoverCharge(new BigDecimal(0)).qualityProductsProcurement(new BigDecimal(0))
							.innovationProductsProcurement(new BigDecimal(0)).creditEnterprisesProcurement(new BigDecimal(0))
							.remarkNumber(0).build()));
			two.setChildVOS(twoList);


			for (PageData pd : firstCompanys){
				//当单位参数不为空时进行判断
				if (CollectionUtil.isNotEmpty(fillingUnitIds) && !fillingUnitIds.contains(pd.get("id"))){
					continue;
				}
				ProcurementSummaryVO initVO = ProcurementSummaryVO.builder().index(String.valueOf(index))
						.fillingUnitId((String)pd.get("id")).fillingUnitName((String)pd.get("name"))
						.totalBudget(new BigDecimal(0)).totalProjectNumber(0).totalContractAmount(new BigDecimal(0))
						.totalCoverCharge(new BigDecimal(0)).totalQualityProducts(new BigDecimal(0)).totalInnovationProducts(new BigDecimal(0))
						.totalCreditEnterprises(new BigDecimal(0)).build();
				List<ProcurementSummaryChildVO> childVOS = new ArrayList<>();
				procurementCategoryMap.forEach((k,v) ->
						childVOS.add(ProcurementSummaryChildVO.builder().procurementCategoryId(k).procurementCategoryName(v).build()));

				initVO.setChildVOS(childVOS);
				init.add(initVO);
				index++;

			}
		}

		return init;
	}

}
